/*
 * @Author: Xiao Xiang Lun
 * @LastEditors: Xiao Xiang Lun
 * @Date: 2021-06-16 14:24:33
 * @LastEditTime: 2021-06-24 18:04:46
 * @FilePath: /projects/intelligence-application/src/utils/imgToZip.js
 * @Environment: Win 10 node.js V 12.13.0
 * @Description:
 */

import axios from 'axios'
import JSZip from 'jszip'
import FileSaver from 'file-saver'

// 获取文件pomise对象
interface GetFile {
  (url: string): Promise<ArrayBuffer>;
}

const getFile: GetFile = (url) => {
  return new Promise<ArrayBuffer>((resolve, reject) => {
    axios({
      method: 'get',
      url,
      responseType: 'arraybuffer'
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.toString())
    })
  })
}

interface ValidateContainJPG {
  (name: string): string;
}

const validateContainJPG: ValidateContainJPG = (name) => {
  const REG = /.*\.jpg$/;
  return REG.test(name) ? name : name + '.jpg';
};

interface HandleImgToArchive {
  (urlList: string[], VUE_APP_IMAGE_PROXY: string): Promise<boolean>;
}

interface Cache {
  [key: string]: ArrayBuffer;
}

interface PromiseArr {
  (item: string, index: number): void;
}

const handleImgToArchive: HandleImgToArchive = async (urlList, VUE_APP_IMAGE_PROXY) => {
  console.log(VUE_APP_IMAGE_PROXY);
  const list: string[] = urlList;
  const zip = new JSZip();
  const cache: Cache = {};
  const promiseArr: Promise<void>[] = [];
  let flag = false;

  list.forEach((item, index) => {
    if (item) {
      const promise = getFile(item).then(res => {
        const arrName = item.split('/');
        const [last_file_name, ...args] = [...arrName].reverse();
        zip.file(validateContainJPG(index.toString()), res, {
          binary: true
        }); // 逐个添加文件
        cache[last_file_name] = res;
      }).catch(err => {
        console.log('catch', flag);
        flag = true;
      });
      promiseArr.push(promise);
    }
  });

  if (flag) return Promise.resolve(true);

  return new Promise<boolean>((resolve, reject) => {
    Promise.all(promiseArr).then(() => {
      zip.generateAsync({
        type: 'blob'
      }).then(content => { // 生成二进制流
        FileSaver.saveAs(content, 'photos.zip'); // 利用file-saver保存文件
        resolve(false);
      }).catch(err => {
        reject(err);
      });
    });
  });
};

export default handleImgToArchive;
